﻿using HtmlAgilityPack;
using System.Collections.Generic;
using System.Diagnostics;
using TheLocal.Model;
using System.Linq;
using System;

namespace TheLocal.Core
{
    public class Parser
    {
        public Parser()
        {
        }

        public List<NewsItem> GetNewsSummaryFromHtml(string html)
        {
            HtmlDocument doc = new HtmlDocument();
            doc.LoadHtml(html);

            var nodes = GetNodesWithIdValue(doc.DocumentNode, "newsSummary");
            List<NewsItem> news = new List<NewsItem>();

            foreach (HtmlNode node in nodes)
            {
                news.Add(this.CreateNewsItemFromNewsSummary(node));
            }

            return news;
        }

        public string GetNewsContentFromHtml(string html)
        {
            HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(html);

            HtmlNode news = GetNodeWithIdValue(doc.DocumentNode, "col1");
            HtmlNode newsDetails = GetNodeWithIdValue(news, "KonaBody");

            HtmlNode heading = news.ChildNodes.Where(node => node.Name == "h1" || node.Name == "h2").FirstOrDefault();
            HtmlNode image = news.ChildNodes.Where(node => node.Name == "img").FirstOrDefault();

            HtmlNode uiToRemove = newsDetails.ChildNodes.FindFirst("ul");

            if (uiToRemove != null)
                uiToRemove.Remove();

            HtmlNode divToRemove = newsDetails.ChildNodes.FindFirst("div");

            if (divToRemove != null)
                divToRemove.Remove();

            return newsDetails.InnerText.Trim();
        }

        private NewsItem CreateNewsItemFromNewsSummary(HtmlNode newsSummary)
        {
            HtmlNode linkTag = newsSummary.Descendants().First(node => node.Name == "a");
            IEnumerable<HtmlNode> descendants = newsSummary.Descendants();
            var imageLink = string.Empty;

            var description = descendants.FirstOrDefault(node => node.Name == "p").InnerText;
            var title = descendants.FirstOrDefault(node => node.Name == "a").InnerText;
            HtmlNode imageNode = descendants.FirstOrDefault(node => node.Name == "img");
            if (imageNode != null)
            {
                imageLink = imageNode.Attributes[0].Value;
                if (string.IsNullOrEmpty(title))
                {
                    title = imageNode.Attributes[2].Value;
                }
            }
            var articlePath = descendants.FirstOrDefault(node => node.Name == "a").Attributes[0].Value;

            return new NewsItem()
            {
                Description = description,
                ImagePath = imageLink,
                ArticlePath = articlePath,
                Title = title
            };
        }

        private HtmlNode GetNodeWithAttributeName(HtmlNode currentNode, string attributeName)
        {
            return currentNode.Descendants().Where(node => node.Attributes.Where(attribute => attribute.Name == attributeName).Count() != 0).FirstOrDefault();
        }

        private HtmlNode GetNodeWithIdValue(HtmlNode currentNode, string attributeValue)
        {
            HtmlNode news = currentNode.Descendants().Where(node => node.Attributes.Where(attribute => attribute.Value == attributeValue).Count() != 0).FirstOrDefault();
            return news;
        }

        private IEnumerable<HtmlNode> GetNodesWithIdValue(HtmlNode currentNode, string attributeValue)
        {
            return currentNode.Descendants().Where(node => node.Attributes.Where(attribute => attribute.Value == attributeValue).Count() != 0);
        }

        /*
         *  HtmlDocument doc = new HtmlDocument();

            doc.LoadHtml(e.Result);

            HtmlNode news = GetNodeWithIdValue(doc.DocumentNode, "col1");
            HtmlNode newsDetails = GetNodeWithIdValue(news, "KonaBody");

            HtmlNode heading = news.ChildNodes.Where(node => node.Name == "h1" || node.Name == "h2").FirstOrDefault();
            HtmlNode image = news.ChildNodes.Where(node => node.Name == "img").FirstOrDefault();

            HtmlNode uiToRemove = newsDetails.ChildNodes.FindFirst("ul");

            if (uiToRemove != null)
                uiToRemove.Remove();

            HtmlNode divToRemove = newsDetails.ChildNodes.FindFirst("div");

            if (divToRemove != null)
                divToRemove.Remove();

            this.NewsHeadingTextBlock.Text = heading.InnerText;

            ParseText(newsDetails.InnerText.Trim());

            WebClient webClientImgDownloader = new WebClient();
            webClientImgDownloader.OpenReadCompleted += new OpenReadCompletedEventHandler(webClientImgDownloader_OpenReadCompleted);

            if (image != null)
            {
                string url = image.GetAttributeValue("src", String.Empty);

                webClientImgDownloader.OpenReadAsync(new Uri(string.Format("{0}{1}", MainViewModel.TheLocalUri, url)));
            }
         *
         */
    }
}
